<template>
  <view class="fast-login-wrapper">
    <!-- 未注册用户 -->
    <!-- <button
      v-if="!hasInfo && type === 'userinfo'"
      class="btn-login"
      open-type="getUserInfo"
      @tap.stop
      @getuserinfo.stop="fastLogin"
    >
      <slot/>
    </button> -->

    <!-- 未注册用户 -->
    <!-- <button
      v-else-if="!hasMobile && type === 'mobile'"
      class="btn-login"
      open-type="getPhoneNumber"
      @tap.stop
      @getphonenumber.stop="fastLogin"
    >
      <slot/>
    </button> -->

    <block v-if="!hasInfo">
      <button class="btn-login" @tap.stop="getUserProfile">
        <slot />
      </button>
    </block>
    <block v-else>
      <button class="btn-login" @tap.stop="onSuccess">
        <slot />
      </button>
    </block>
  </view>
</template>

<script lang="ts">
/**
 * 快速登录组件
 * @author michaelZ
 */
// @ts-nocheck
import { Vue, Component, Prop, Mixins } from "vue-property-decorator";
import { loginMixin } from "@/mixins";
import { throttle } from "utils-decorators";

@Component
export default class FastLogin extends Mixins(loginMixin) {
  // 获取基本信息 or 手机号
  @Prop() type: string;
  @Prop() index: number;

  get userInfo() {
    return this.$$store;
  }

  get hasInfo() {
    return this.$$store.userInfo.user && this.$$store.userInfo.user.nickname;
  }

  get hasMobile() {
    return this.$$store.userInfo.user && this.$$store.userInfo.user.mobile;
  }

  private getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.onSuccess(res.userInfo);
      },
    });
  }

  @throttle(500)
  private fastLogin(e: any) {
    this.type === "userinfo" ? this.getUserinfo(e) : this.getMobile(e);
  }

  // 获取用户基础信息
  private async getUserinfo(e: any) {
    if (e.detail.errMsg === "getUserInfo:ok") {
      const { encryptedData, iv, userInfo } = e.detail;

      this.onSuccess(userInfo);
    }
  }

  // 快速绑定手机号
  private async getMobile(e: any) {
    if (this.hasMobile) {
      this.onSuccess();

      return;
    }

    if (e.detail.errMsg === "getPhoneNumber:ok") {
      const { encryptedData, iv } = e.detail;

      this.onSuccess();
    } else {
      wx.showModal({
        title: "提示",
        content: "无法登录？尝试更换手机号",
        success(res) {
          res.confirm && uni.navigateTo({ url: "/subPages/register/index" });
        },
      });
    }
  }

  // 获取身份信息 or 手机号成功 || 已登录
  @throttle(500)
  private onSuccess(userInfo?: any) {
    this.$emit("success", {
      type: this.type,
      index: this.index,
      userInfo,
    });
  }
}
</script>

<style lang="scss" scoped>
button.btn-login {
  padding: 0;
  background: transparent;
  line-height: unset;
  min-height: unset;
  width: 100%;
  font-weight: unset;
  font-size: unset;
  text-align: unset;
  color: unset;
  overflow: visible;

  &::after {
    border: none;
  }
}
</style>
